<template>
  <div class="details_page">
    <!-- <v-head headTitle="确认兑换">
    </v-head>-->
    <div class="content">
      <!-- 页头产品展示信息 -->
      <div class="goods-cell">
        <div class="pic-box">
          <img :src="imgBaseUrl+details.ico" :alt="details.title" />
        </div>
        <div class="detail">
          <h2 class="name">{{details.title}}</h2>
          <!-- <p class="stock">
            <span>剩余：{{details.limitNum}}</span>
          </p>-->
          <p class="integral">
            <span class="color_red">
              <span class="color_span">总价：</span>
              {{details.price?details.price:0}}元
            </span>
          </p>
          <p class="integral">
            <span class="color_red">
              <span class="color_span">积分：</span>
              {{vipuser == '1'?details.vipCoin:details.coin}}积分
            </span>
          </p>
          <!-- <del class="delsty">原价：{{details.oPrice}}</del> -->
          <!-- <p class="time" v-if="details.deadline">使用有效期：{{details.deadline}}</p> -->
        </div>
      </div>
      <!-- 列表，有些显示需满足条件 -->
      <div>
        <van-cell title="购买数量">
          <van-stepper :disabled="true" v-model="buyNum" />
        </van-cell>
        <!-- <van-field
          v-model="name"
          type="textarea"
          :disabled="orderId?true:false"
          label="姓名"
          placeholder="请输入您的真实姓名"
          rows="1"
          clearable
          autosize
          maxlength="20"
          :error-message="res"
          @blur="nameRes()"
        />
        <van-field
          v-model="telNumber"
          :disabled="orderId?true:false"
          label="手机号"
          type="textarea"
          placeholder="请输入正确手机号"
          :error-message="telRes"
          rows="1"
          clearable
          autosize
          @blur="telReq()"
        />
        <van-field
          v-model="codeVal"
          v-if="!orderId"
          center
          clearable
          label="验证码"
          placeholder="请输入短信验证码"
          :error-message="codeRes"
          @blur="codeNum()"
        >
          <div
            v-if="show"
            class="codeBtn"
            @click="getCode()"
            slot="button"
          >获取验证码</div>
          <span
            v-else
            slot="icon"
          >{{count}} s</span>
        </van-field>-->

        <van-field
          v-model="username"
          type="textarea"
          label="姓名"
          rows="1"
          clearable
          autosize
          :error-message="res"
          @blur="nameRes()"
        />
        <van-field
          v-model="usertel"
          type="textarea"
          :label="productId == '572' || productId == '573' || productId == '1128'?'充值手机号' : '手机号'"
          rows="1"
          :error-message="telRes"
          clearable
          autosize
          @blur="telReq()"
        />
        <van-field
          v-if="needId"
          v-model="cardId"
          type="textarea"
          :disabled="orderId?true:false"
          label="身份证"
          placeholder="请输入身份证号码"
          :error-message="cardRes"
          rows="1"
          clearable
          autosize
          @blur="cardReq()"
        />
        <van-field
          v-if="needAddress"
          v-model="address"
          :disabled="orderId?true:false"
          label="收货地址"
          type="textarea"
          placeholder="请输入收货地址（限厦门）"
          rows="1"
          clearable
          autosize
          @blur="addressReq()"
        />
        <van-field
          v-if="needLicenseNo"
          v-model="LicenseNo"
          type="textarea"
          :disabled="orderId?true:false"
          label="车牌号"
          placeholder="请输入车牌号"
          :error-message="LicenseNoRes"
          rows="1"
          clearable
          autosize
          @blur="LicenseNoReq()"
        />
        <van-field v-model="remark" label="备注" type="textarea" rows="1" clearable autosize />
        <van-cell
          v-if="needDate"
          title="使用日期"
          is-link
          @click="!orderId?showCalendar=true:showCalendar=false"
          :value="useDate"
        />
        <!-- <van-cell title="满减权益" :is-link="!orderId?true:false">
          <div class="coupon_list">
            <router-link
              v-if="!orderId"
              :to="{path:'/points/detail/status/mycoupon',query:{price:price,toclick:this.toclick}}"
            >
              <span
                :class="hasCanUseCoupon<=0?'none_coupon_list':'coupon_list'"
                v-text="hasCanUseCoupon <= '0'?'无满减权益可用':choiseCoupon.coupon?'-￥'+choiseCoupon.coupon.discountValue:hasCanUseCoupon+'张可用(点击使用可抵扣)'"
              />
            </router-link>
            <span
              v-else
              class="none_coupon_list"
              v-text="'-￥' + (orderDetail.totalPrice-orderDetail.shouldPayPrice).toFixed(2)"
            ></span>
          </div>
        </van-cell>-->
        <span class="warn_info"></span>
        <van-cell title="支付方式" />
        <van-radio-group class="pay_way" v-model="radio">
          <van-cell-group>
            <!-- <van-cell clickable @click="radio = '2'">
              <template slot="title">
                <img src="@/assets/images/yunpay.png" alt class="yun_icon" />
                <span class="custom-text">云闪付</span>
              </template>
              <van-radio name="2" checked-color="#1c4237" class="radio" />
            </van-cell> -->
            <van-cell clickable @click="radio = '1'">
              <template slot="title">
                <img src="@/assets/images/wxpay.png" alt class="wx_icon" />
                <span class="custom-text">微信支付</span>
              </template>
              <van-radio name="1" checked-color="#1c4237" class="radio" />
            </van-cell>
          </van-cell-group>
        </van-radio-group>
      </div>

      <!-- 底部的总计积分和按钮 -->
      <div class="fixed-bar">
        <div class="total">
          <span
            class="color_red"
            v-text="(vipuser == '1'?details.vipCoin+'积分':details.coin+'积分')+'+'+(price>0?price+'元':'')"
          ></span>
          <!-- <span v-else class="color-red" v-text="'￥'+orderDetail.shouldPayPrice"></span> -->
          <!-- <span
            v-if="choiseCoupon.coupon"
            class="discountValue"
          >已优惠￥{{choiseCoupon.coupon.discountValue}}</span>-->
        </div>
        <button class="btn" @click="toOrder">立即支付</button>
      </div>
    </div>
    <!-- 日历 -->
    <van-popup v-model="showCalendar" position="bottom">
      <calendar-el
        style="height:400px; padding-top: 20px;"
        :aroud="calendar.aroud"
        :click-action="setCurrentDate"
        :nums="calendar.nums"
        :select-date="currentDate"
        :isAll="isAll"
      ></calendar-el>
    </van-popup>
    <transition name="router-slid" mode="out-in">
      <router-view></router-view>
    </transition>
  </div>
</template>

<script>
import {
  Field,
  Button,
  Dialog,
  Popup,
  Picker,
  Cell,
  CellGroup,
  Toast,
  Stepper,
  RadioGroup,
  Radio,
  Icon
} from 'vant';
import calendarEl from '@/components/calendar2';
// import moment from 'moment';
import { imgBaseUrl } from '@/config/env';
export default {
  data() {
    return {
      productId: '',
      telRes: '',
      remark: '',
      username: '',
      usertel: '',
      imgBaseUrl,
      list: [],
      id: '',
      orderId: '',
      orderDetail: {}, // 我的订单过来的时候的用户填写的信息
      details: {},
      res: '',
      cardRes: '',
      LicenseNoRes: '',
      cardId: '', // 身份证
      address: '福建省厦门市',
      addressRes: '',
      LicenseNo: '',
      showSlect: false,
      showCalendar: false,
      buyNum: '1', // 购买数量
      needId: false, // 是否需要身份证
      needDate: true, // 是否为价格日历
      needAddress: false, // 是否需要填写地址
      needLicenseNo: false, // 是否需要填写车牌号
      radio: '1', // 支付方式
      codeRes: '',
      codeVal: '',
      calendar1: {
        begin: [
          new Date().getFullYear(),
          new Date().getMonth() + 1,
          new Date().getDate()
        ],
        lunar: true, // 显示农历
        select(value) {
          console.log(value.toString());
        }
      },
      useDate: '',
      calendar: {
        open: false,
        aroud: 2, // 12个月
        nums: []
      },
      currentDate: null, // 当前选择的日期
      isAll: true, // 是否所有日期可选
      couponList: [], // 优惠券列表
      hasCanUseCoupon: 0, // 可使用的优惠券数量
      choiseCoupon: {}, // 已选择的优惠券信息
      price: '',
      timer: '',
      show: true,
      isAuth: true, // 是否已实名
      hasInCoupon: false, // 防止更改产品数量反复弹窗的问题
      count: '',
      seckillId: '',
      vipuser: ''
    };
  },
  mounted() {
    const id = this.$route.query.id + '';
    const order = this.$route.query.order;
    if (!order) {
      this.id = id;
      this.currentUserInfo();
    } else {
      this.id = id;
      this.orderId = order;
      this.getDetails(id);
      this.getOrderInfo(order);
      this.currentUserInfo();
    }
  },
  methods: {
    // 获取用户信息
    currentUserInfo() {
      this.$http.post('/tuser/userInfo', {}).then(res => {
        if (res.data.code === '0') {
          if (res.data.object.isAuth === '0') {
            this.isAuth = false;
            // 未实名
            Dialog.confirm({
              title: '提示',
              message: '您尚未实名',
              confirmButtonText: '前往实名',
              cancelButtonText: '返回'
            })
              .then(() => {
                this.$router.replace('/real_name');
              })
              .catch(() => {
                this.$router.go(-1);
              });
          } else {
            this.username = res.data.object.username;
            this.usertel = res.data.object.telphone;
            this.vipuser = res.data.object.isVip;
            this.isAuth = true;
          }
          this.getDetails(this.id);
        } else {
          Dialog.alert({
            title: '提示',
            message: res.data.message
          }).then(() => {
            this.$route.go(-1);
          });
        }
      });
    },
    getOrderInfo(id) {
      this.$http.post('/order/detail', { orderId: id }).then(res => {
        console.log(res);
        if (res.data.code === '0') {
          this.orderDetail = res.data.object;
          this.telNumber = res.data.object.telphone;
          this.name = res.data.object.receiver;
          this.cardId = res.data.object.idNo;
          this.useDate = res.data.object.useDate;
          this.address = res.data.object.address;
          this.codeVal = res.data.object.code;
          this.LicenseNo = res.data.object.licenseNo;
          this.userCouponId = res.data.object.userCouponId;
          this.buyNum = res.data.object.amount;
        } else {
          Dialog.alert({
            message: '获取信息失败'
          }).then(res => {
            this.$router.go(-1);
          });
        }
      });
    },
    toclick(item) {
      this.choiseCoupon = item;
    },
    getCoupon() {
      this.$http
        .post('/tuserCoupon/list', {
          isUse: 0,
          pageSize: 1000
        })
        .then(res => {
          let num = 0;
          if (res.data.list.length > 0) {
            this.list = res.data.list;
            res.data.list.map(item => {
              console.log(item.coupon.faceValue + '*****' + this.price);
              if (item.coupon.faceValue <= this.price) {
                num++;
                this.choiseCoupon = item;
              }
            });
          } else {
            console.log(this.hasInCoupon);
            console.log(this.isAuth);
            if (!this.hasInCoupon && this.isAuth) {
              this.hasInCoupon = true;
              Dialog.confirm({
                title: '提示',
                message: '您还未兑换满减权益,是否兑换?',
                confirmButtonText: '前往积分兑换权益'
              }).then(() => {
                this.$router.push('/equity');
              });
            }
          }
          this.hasCanUseCoupon = num;
        });
    },
    setCurrentDate(d) {
      this.currentDate = d; //
      this.useDate =
        d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
      this.showCalendar = false;
      console.log(this.useDate);
    },
    codeNum() {
      if (this.codeVal) {
        this.codeRes = '';
      } else {
        this.codeRes = '请输入验证码';
      }
    },
    getDetails(data) {
      this.$http.post('/seckill/product', { id: data }).then(res => {
        console.log(res.data);
        if (res.data.code === '0') {
          const result = res.data.object;
          this.details = result;
          this.price = result.price;
          this.productId = result.productId;
          this.seckillId = result.seckillId;
          this.needId = Boolean(result.needId === '1');
          this.needDate = Boolean(result.needDate === '1');
          this.needAddress = Boolean(result.needAddress === '1');
          this.needLicenseNo = Boolean(result.needLicenseNo === '1');
          // this.getCoupon();
          // this.isAll = Boolean(result.platform === '8');
        }
      });
    },
    checkForm() {
      let isOk = true;
      if (this.needId) {
        if (this.cardId.match(/^\d{15}(\d\d[0-9xX])?/)) {
          this.cardRes = '';
        } else {
          this.cardRes = '身份证格式不正确';
          isOk = false;
          Toast.fail('身份证格式不正确');
        }
      }
      if (this.needLicenseNo) {
        if (this.LicenseNo.trim().length < 7) {
          this.LicenseNoRes = '请输入车牌号';
          isOk = false;
          Toast.fail('请输入车牌号');
        } else {
          this.LicenseNoRes = '';
        }
      }
      if (this.needDate) {
        if (!this.useDate) {
          isOk = false;
          Toast.fail('请选择配送日期');
        }
      }
      if (this.needAddress) {
        if (this.address.trim().length < 7) {
          isOk = false;
          this.addressRes = '请输入详细地址（限制厦门地区）';
          Toast.fail('请输入详细地址（限制厦门地区）');
        } else {
          this.addressRes = '';
        }
      }
      return isOk;
    },
    getCode() {
      const TIME_COUNT = 60;
      if (this.telNumber.match(/^[1][3,4,5,6,7,8,9][0-9]{9}$/)) {
        this.$http
          .post('/entrance/getSmsCode', {
            telphone: this.telNumber,
            source: '1'
          })
          .then(result => {
            if (result) {
              if (result.data.code === '0') {
                Toast('发送成功');
              } else {
                Toast(result.data.message);
                return;
              }
            }
          });
      } else {
        Toast('请输入正确手机号码');
        return;
      }
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.show = false;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.show = true;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    },
    toOrder() {
      if (!this.checkForm()) {
        return;
      }
      // if (moment().isBefore('2019-12-21')) {
      if (!this.orderId) {
        this.$http
          .post('/order/add', {
            distributor: window.sessionStorage.getItem('distributor')
              ? window.sessionStorage.getItem('distributor')
              : '',
            productId: this.productId,
            // telphone: this.telNumber,
            // receiver: this.name.trim(),
            idNo: this.cardId,
            useDate: this.useDate,
            address: this.address.trim(),
            // code: this.codeVal,
            licenseNo: this.LicenseNo,
            userCouponId: this.choiseCoupon.coupon ? this.choiseCoupon.id : '',
            amount: this.buyNum, // 购买数量
            remark: this.remark,
            telphone: this.usertel,
            receiver: this.username,
            source: 'secKill',
            secKillId: this.seckillId
          })
          .then(res => {
            if (res) {
              if (res.data.code === '0') {
                this.toppay(res.data.object);
              } else {
                Dialog.alert({
                  message: res.data.message
                });
              }
              console.log(res);
            }
          });
      } else {
        this.toppay(this.orderId);
      }
      // } else {
      //   Dialog.alert({
      //     confirmButtonColor: '#28b46a',
      //     title: '提示',
      //     message:
      //       '邮储积分兑换活动已于2019年12月20日结束，已兑换产品请于2019年12月31日前核销，来不及核销的产品请自行保存好卡号卡密等关键信息，本活动链接将于2019年12月31日后开始升级，升级后所有记录清零！'
      //   }).then(() => {
      //     window.history.go(-1);
      //   });
      // }
    },
    toppay(index) {
      this.$http
        .post('/order/topay', {
          orderId: index.toString(),
          // payType: this.radio
          payType: '3'
        })
        .then(res => {
          console.log(res);
          if (res.data.code === '0') {
            if (this.radio === '1') {
              window.location.href = res.data.object.wechatPayURL;
            } else if (this.radio === '2') {
              document.write(res.data.object.htmlForm);
            }
          } else if (res.data.code === '2') {
            if (res.data.message === '交易失败[交易金额超出上限]') {
              Dialog.alert({
                message: '交易失败[交易金额超出上限]'
              });
            } else {
              Dialog.alert({
                message: '支付异常，请重新支付'
              }).then(() => {
                this.$router.replace('seckillmodel');
              });
            }
          } else if (res.data.code === '3') {
            Dialog.alert({
              message: res.data.message
            }).then(() => {
              this.$router.replace('seckillmodel');
            });
          } else {
            Dialog.alert({
              message: '支付异常，请重新支付'
            }).then(() => {
              this.$router.replace('seckillmodel');
            });
          }
        });
    },
    nameRes() {
      if (this.username) {
        if (this.username.trim().length > 1) {
          this.res = '';
        } else {
          this.res = '姓名格式不正确';
        }
      } else {
        this.res = '姓名不能为空';
      }
    },
    addressReq() {
      if (this.address.trim().length < 7) {
        this.addressRes = '请输入详细地址（限制厦门地区）';
      } else {
        this.addressRes = '';
      }
    },
    LicenseNoReq() {
      if (this.LicenseNo.trim().length < 7) {
        this.LicenseNoRes = '请输入车牌号';
      } else {
        this.LicenseNoRes = '';
      }
    },
    telReq() {
      if (this.usertel.match(/^[1][3,4,5,6,7,8,9][0-9]{9}$/)) {
        this.telRes = '';
      } else {
        this.telRes = '手机号码格式不正确';
      }
    },
    cardReq() {
      if (this.cardId.match(/^\d{15}(\d\d[0-9xX])?/)) {
        this.cardRes = '';
      } else {
        this.cardRes = '身份证格式不正确';
      }
    }
  },
  watch: {
    buyNum() {
      this.price = (this.buyNum * this.details.price).toFixed(2);
      // this.getCoupon();
      if (
        this.choiseCoupon.coupon &&
        this.choiseCoupon.coupon.faceValue > this.buyNum * this.details.price
      ) {
        this.choiseCoupon = {};
        this.orderId = '';
      }
      return this.price;
    }
  },
  components: {
    calendarEl,
    'van-field': Field,
    'van-popup': Popup,
    'van-picker': Picker,
    'van-cell': Cell,
    'van-cell-group': CellGroup,
    'van-button': Button,
    'van-stepper': Stepper,
    'van-radio-group': RadioGroup,
    'van-radio': Radio,
    'van-icon': Icon
  }
};
</script>

<style lang="scss" scoped>
.van-picker__toolbar {
  font-size: 40px;
}
.content {
  padding-bottom: 120px;
  width: 100%;
  height: 100%;
  overflow: scroll;
  .codeBtn {
    color: #28b46a;
  }
  .coupon_list {
    span {
      font-size: 26px;
    }
    .none_coupon_list {
      color: #959595;
    }
    .coupon_list {
      color: red;
      padding-left: 15px;
    }
  }
  .warn_info {
    color: red;
    height: 70px;
    line-height: 70px;
    margin-left: 30px;
    font-size: 24px;
  }
  .pay_way {
    .wx_icon {
      width: 40px;
      height: 36px;
      margin-right: 8px;
    }
    .yun_icon {
      width: 48px;
      height: 46px;
    }
  }
}

.details_page {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ebebeb;
  z-index: 101;
  width: 100%;
  height: 100%;
}
.goods-cell {
  padding: 20px;
  display: flex;
  align-items: center;
  background-color: #ffffff;
  margin-bottom: 25px;
  .pic-box {
    width: 200px;
    height: 200px;
    flex: 0 0 200px;
    margin-right: 16px;
    img {
      max-width: 200px;
      max-height: 200px;
    }
  }
  .detail {
    flex-direction: column;
    justify-content: center;
    display: flex;
    height: 2.666667rem;
    @include sc(30px, #3b3b3b);
    p {
      margin-top: 5px;
    }
    .name {
      font-size: 30px;
      font-weight: 400;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      width: 418px;
    }
    .time {
      @include sc(28px, #7f7d7d);
    }
    .stock {
      // border-radius: 8px;
      // border: solid 1px #ff0000;
      // @include sc(30px, #ff0000);
      // max-width: 200px;
      span {
        @include sc(30px, #fe5568);
        border-radius: 8px;
        border: solid 1px #fe5568;
        padding: 10px;
      }
    }
    .color_span {
      font-size: 26px;
      color: #a3a3a3;
    }
    .delsty {
      font-size: 26px;
      color: #8d8d8d;
    }
  }
}
.fixed-bar {
  width: 100%;
  display: flex;
  position: fixed;
  bottom: 0;
  height: 88px;
  background-color: #ffffff;
  .total {
    width: 60%;
    @include sc(32px, #1c1c1e);
    display: flex;
    align-items: center;
    justify-content: center;
    span {
      display: block;
      margin: 0 15px;
      font-size: 38px;
    }
    .discountValue {
      font-size: 30px;
      padding-left: 15px;
      color: #939393;
      border-left: 1px solid #acacac;
    }
  }
  button {
    border: none;
    background-color: #1c4237;
    width: 40%;
    @include sc(32px, #fafafb);
    &.disabled {
      background-color: #b7b6b7;
      font-size: 30px;
    }
    p {
      font-size: 24px;
    }
  }
}
.color_red {
  color: #fe5568;
}
.radio {
  padding-left: 300px;
}
</style>
